package org.jeecg.modules.quartz.job;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.ZrkCollectionRate;
import io.finer.erp.jeecg.bas.entity.ZrkOrderSalary;
import io.finer.erp.jeecg.bas.entity.ZrkSalaryCal;
import io.finer.erp.jeecg.bas.entity.ZrkYwSalary;
import io.finer.erp.jeecg.bas.service.IZrkCollectionRateService;
import io.finer.erp.jeecg.bas.service.IZrkOrderSalaryService;
import io.finer.erp.jeecg.bas.service.IZrkSalaryCalService;
import io.finer.erp.jeecg.bas.service.IZrkYwSalaryService;

@Component
public class YwSalaryJob implements Job {
	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private IZrkYwSalaryService zrkYsSalaryService;
	
	@Autowired
	private IZrkSalaryCalService zrkSalaryCalService;

	@Autowired
	private IZrkOrderSalaryService zrkOrderSalaryService;

	@Autowired
	private IZrkCollectionRateService zrkCollectionRateService;


	/**
	 * 定时任务计算业务员薪资----每月20号中午执行
	 */
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		//获取所有业务员（查询数据库中角色为业务的用户）
		List<SysUser> suList=sysUserService.getUserByRoleIdAndNoPage("1306788343273226242");
		//判断是否获取到业务员列表
		if(null!=suList&&suList.size()>0) {
			//点击按钮后获取当前月份
			int month=DateUtils.getMonth();
			//获取当前年
			int year=DateUtils.getYear();
			for(SysUser su:suList) {
				//获取业务员提成、薪资计算日等参数
				ZrkYwSalary zrkYwSalary=zrkYsSalaryService.getByUserId(su.getId());
				if(null == zrkYwSalary) {
					continue;
				}
				//查询回款率设置参数
				QueryWrapper<ZrkCollectionRate> queryWrapper=new QueryWrapper<ZrkCollectionRate>();
				ZrkCollectionRate zcr=zrkCollectionRateService.getOne(queryWrapper.last("LIMIT 1"));
				//拼接工资起止日期，如：2020-07-20-----2020-08-20
				String startTime=year+"-"+(month-2)+"-"+zrkYwSalary.getCalDate();
				String endTime=year+"-"+(month-1)+"-"+zrkYwSalary.getCalDate();
				QueryWrapper<ZrkOrderSalary> qw=new QueryWrapper<ZrkOrderSalary>();
				qw.gt("overtime", endTime);//最高有效期大于当前时间
				qw.and(wrapper->wrapper.eq("salary_status", "1"));
				qw.and(wrapper->wrapper.eq("salary_status", "1"));
				qw.and(wrapper->wrapper.eq("is_all_money", "1"));
				qw.and(wrapper->wrapper.eq("money_type", "2"));
				qw.and(wrapper->wrapper.eq("user_id", su.getId()));
//				qw.eq("salary_status", "1");//查询未计算的
//				qw.eq("is_all_money", "1");//查询回全款的
//				qw.eq("money_type", "2");//查询账期回款记录
//				qw.eq("user_id", su.getId());//设置业务员
				BigDecimal oldTotalCashMoney=BigDecimal.ZERO;
				BigDecimal newTotalCashMoney=BigDecimal.ZERO;
				BigDecimal oldTotalPeriodMoney=BigDecimal.ZERO;
				BigDecimal newTotalPieriodMoney=BigDecimal.ZERO;
				List<ZrkOrderSalary> needCalSalaryList=zrkOrderSalaryService.list(qw);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Map<String,BigDecimal> map=newOrOldCusPeriodMoney(zcr, oldTotalPeriodMoney, newTotalPieriodMoney, needCalSalaryList, sdf);
				//查询现金回款信息
				Map<String,BigDecimal> mp=calCashTC(startTime, endTime, oldTotalCashMoney, newTotalCashMoney);
				BigDecimal newCus=map.get("newCus").add(mp.get("newCus"));
				BigDecimal oldCus=map.get("oldCus").add(mp.get("oldCus"));
				BigDecimal yqMoney=map.get("yqMoney").add(mp.get("yqMoney"));
				//记录生成的当月业务员工资信息
				ZrkSalaryCal zsc=new ZrkSalaryCal();
				zsc.setCreateTime(DateUtils.getDate());
				zsc.setUserId(su.getId());
				zsc.setIsFinish(0);//将状态置为未发放
				zsc.setNoSalary(yqMoney);
				zsc.setCurrentSalary(newCus.add(oldCus));//设置当月提成
				zsc.setBaseSalary(zrkYwSalary.getBaseSalary());
				zrkSalaryCalService.save(zsc);//提交数据库
			}
		}
	}

	/**
	 * 
	* @Title: calCashTC 
	* @Description: 计算新老现金客户提成
	* @author heckerstone heckerstone@163.com
	* @date Sep 19, 2020 11:23:57 AM 
	* @param @param startTime
	* @param @param endTime
	* @param @param oldTotalCashMoney
	* @param @param newTotalCashMoney    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private Map<String,BigDecimal> calCashTC(String startTime, String endTime, BigDecimal oldTotalCashMoney,BigDecimal newTotalCashMoney) {
		Map<String,BigDecimal> map=new HashMap<String,BigDecimal>();
		BigDecimal yqMoney=BigDecimal.ZERO;
		QueryWrapper<ZrkOrderSalary> cqw=new QueryWrapper<ZrkOrderSalary>();
		cqw.eq("money_type", "1");//现金回款类型
		cqw.and(wrapper->wrapper.between("order_time", startTime, endTime));
//		cqw.between("orderTime", startTime, endTime);
		List<ZrkOrderSalary> cashList=zrkOrderSalaryService.list(cqw);
		if(null!=cashList&&cashList.size()>0) {
			for(ZrkOrderSalary zos:cashList) {
				yqMoney=yqMoney.add(zos.getThirtyMoney());
				if(zos.getIsNewOrOld()==1) {
					//新客户
					newTotalCashMoney=newTotalCashMoney.add(zos.getSenventyMoney());
				}else {
					//老客户
					oldTotalCashMoney=oldTotalCashMoney.add(zos.getSenventyMoney());
				}
			}
		}
		map.put("newCus", newTotalCashMoney);
		map.put("oldCus", oldTotalCashMoney);
		map.put("yqMoney", yqMoney);
		return map;
	}

	/**
	 * 
	* @Title: newOrOldCusPeriodMoney 
	* @Description: 新老账期客户计算业务员提成 
	* @author heckerstone heckerstone@163.com
	* @date Sep 19, 2020 11:12:40 AM 
	* @param @param zcr
	* @param @param oldTotalPeriodMoney
	* @param @param newTotalPieriodMoney
	* @param @param needCalSalaryList
	* @param @param sdf    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private Map<String,BigDecimal> newOrOldCusPeriodMoney(ZrkCollectionRate zcr, BigDecimal oldTotalPeriodMoney,BigDecimal newTotalPieriodMoney, List<ZrkOrderSalary> needCalSalaryList, SimpleDateFormat sdf) {
		Map<String,BigDecimal> map=new HashMap<String,BigDecimal>();
		BigDecimal yqMoney=BigDecimal.ZERO;
		if(null!=needCalSalaryList&&needCalSalaryList.size()>0) {
			for(ZrkOrderSalary zos:needCalSalaryList) {
				int day=0;
				try {
					day=DateUtils.dateDiff('d', DateUtils.parseCalendar(DateUtils.getDate("yyyy-MM-dd"), "yyyy-MM-dd"), DateUtils.parseCalendar(DateUtils.date2Str(zos.getEndTime(), sdf), "yyyy-MM-dd"));
				} catch (ParseException e) {
		            day=0;
				}
				//计算延期发放金额总和
				yqMoney=yqMoney.add(zos.getThirtyMoney());
				if(zos.getIsNewOrOld()==1) {
					//新客户
					//账期回款
					//newTotalPieriodMoney=newTotalPieriodMoney.add(zos.getSalesMoney());
					//判断回款时间
					if(day<0) {
						//全额回款并且未超期（计算公式）
						newTotalPieriodMoney=newTotalPieriodMoney.add(zos.getSenventyMoney());
					}else if(day>0){
						//判断超期天数符合那个阶段
						int level1=zcr.getLevelOne();
						int level2=zcr.getLevelTwo();
						int level3=zcr.getLevelThree();
						BigDecimal level1Rate=zcr.getTenRate();
						BigDecimal level2Rate=zcr.getThirtyRate();
						BigDecimal level3Rate=zcr.getSixtyRate();
						//计算公式销售额*新客户提成比例*超期后的比例
						if(day<=level1) {
							//未超10天
							newTotalPieriodMoney=newTotalPieriodMoney.add(zos.getSenventyMoney().multiply(level1Rate));
						}else if(day>level1&&day<=level2) {
							//未超30天
							newTotalPieriodMoney=newTotalPieriodMoney.add(zos.getSenventyMoney().multiply(level2Rate));
						}else if(day>level2&&day<=level3) {
							//未超60天
							newTotalPieriodMoney=newTotalPieriodMoney.add(zos.getSenventyMoney().multiply(level3Rate));
						}
					}
				}else {
					//老客户
					//账期回款
//							oldTotalPeriodMoney=oldTotalPeriodMoney.add(zos.getSalesMoney());
					if(day<0) {
						//全额回款并且未超期（计算公式）
						oldTotalPeriodMoney=oldTotalPeriodMoney.add(zos.getSenventyMoney());
					}else if(day>0) {
						//判断超期天数符合那个阶段
						int level1=zcr.getLevelOne();
						int level2=zcr.getLevelTwo();
						int level3=zcr.getLevelThree();
						BigDecimal level1Rate=zcr.getTenRate();
						BigDecimal level2Rate=zcr.getThirtyRate();
						BigDecimal level3Rate=zcr.getSixtyRate();
						//计算公式销售额*新客户提成比例*超期后的比例
						if(day<=level1) {
							//未超10天
							oldTotalPeriodMoney=oldTotalPeriodMoney.add(zos.getSenventyMoney().multiply(level1Rate));
						}else if(day>level1&&day<=level2) {
							//未超30天
							oldTotalPeriodMoney=oldTotalPeriodMoney.add(zos.getSenventyMoney().multiply(level2Rate));
						}else if(day>level2&&day<=level3) {
							//未超60天
							oldTotalPeriodMoney=oldTotalPeriodMoney.add(zos.getSenventyMoney().multiply(level3Rate));
						}
					}
				}
			}
		}
		map.put("newCus", newTotalPieriodMoney);//新客户应得提成
		map.put("oldCus", oldTotalPeriodMoney);//老客户应得提成
		map.put("yqMoney", yqMoney);
		return map;
	}

	@SuppressWarnings("unused")
	private boolean isNewOrOld(BasCustomer bc, SimpleDateFormat sdf) {
		boolean flag=false;
		try {
			int ye=DateUtils.dateDiff('y', DateUtils.parseCalendar(DateUtils.getDate("yyyy-MM-dd"), "yyyy-MM-dd"), DateUtils.parseCalendar(DateUtils.date2Str(bc.getCreateTime(), sdf), "yyyy-MM-dd"));
			if(ye>1) {
				flag=true;
			}
		} catch (ParseException e) {

		}
		return flag;
	}

}
